package github.saukiya.sxattribute.data.itemdata.sub;

import github.saukiya.sxattribute.SXAttribute;
import github.saukiya.sxattribute.data.itemdata.IGenerator;
import github.saukiya.sxattribute.data.itemdata.ItemDataManager;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.List;

public class GeneratorRandomItem implements IGenerator {

    String pathName;

    String key;

    ConfigurationSection config;

    String pattern;

    String defItem;

    List<String> items;

    public GeneratorRandomItem() {
    }

    public GeneratorRandomItem(String pathName, String key, ConfigurationSection config) {
        this.pathName = pathName;
        this.key = key;
        this.config = config;
        this.items = config.getStringList("Items");
        this.pattern = config.getString("Pattern","global");
        this.defItem = config.getString("DefItem",items.get(items.size()-1));
    }

    @Override
    public JavaPlugin getPlugin() {
        return SXAttribute.getInst();
    }

    @Override
    public String getType() {
        return "random";
    }

    @Override
    public IGenerator newGenerator(String pathName, String key, ConfigurationSection config) {
        return new GeneratorRandomItem(pathName,key,config);
    }

    @Override
    public String getPathName() {
        return pathName;
    }

    @Override
    public String getKey() {
        return key;
    }

    @Override
    public String getName() {
        return getKey();
    }

    @Override
    public ConfigurationSection getConfig() {
        return config;
    }

    @Override
    public ItemStack getItem(Player player) {

        String item = null;
        if (pattern.equalsIgnoreCase("global")){
            item = getItem(SXAttribute.getRandom().nextInt(items.size()-1));
        }else if (pattern.equalsIgnoreCase("order")){
            double randomValue = Math.random() * 1;
            for (String s : items) {
                String[] split = s.split(" ");
                double parseDouble = Double.parseDouble(split[1]);
                if (randomValue < parseDouble){
                    item = split[0];
                    break;
                }
            }
            if (item == null){
                item = defItem;
            }
        }
        return SXAttribute.getItemDataManager().getItem(item,player);
    }

    public String getItem(int index){
        return items.get(index);
    }

    @Override
    public ConfigurationSection saveItem(ItemStack saveItem, ConfigurationSection config) {
        return null;
    }
}
